// pages/takephoto/visitorpicture.js
var Constant = require('../../utils/constant.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageinfo: [],
    itemClick:false,
    isRegister: true,
    animationData: '',
    personcheck: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isRegister: options.isRegister
    })
    getPicList(this)
    scaleButton(this, 0, 0);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    getPicList(this);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  deleteUser: function (e) {
    var index = e.currentTarget.dataset.index;
    var that = this;
    var deleteStr = deleteIdList.join();
    console.log("pass", deleteStr)
    console.log(deleteStr)
    wx.showModal({
      title: '警告',
      content: '确定要删除该访客吗?',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中',
          })

          wx.request({
            url: Constant.BASEURL + Constant.DELETE_VISITER + '&allid=' + deleteStr + "&openid=" + app.globalData.openid,
            method: 'GET',
            success: function (res) {
              console.log(res.data)
              getPicList(that)
              that.setData({
                itemClick: false,
              })
              scaleButton(that, 0, 0);
            },
            complete: function () {
              wx.hideLoading();
            }
          });

        } else {
          console.log("制止了删除")
        }
      }
    })

  },
  //通过授权
  passAuthorization:function(e){
    //获取formId
    console.log("获取的formid：  ", e.detail.formId);
    var formid = e.detail.formId;
    var index = e.currentTarget.dataset.index;
    var that = this;
    console.log("aaaa", deleteIdList.join());
    var deleteStr = deleteIdList.join();


    wx.showModal({
      title: '提示',
      content: '确定要通过该访客的申请吗?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: Constant.BASEURL + Constant.CHANGE_VISITOR_TYPE,
            method: 'POST',
            data:{
              id: deleteStr,
              formid: formid,
            },
            success: function (res) {
              console.log("授权", that.data.imageinfo)
              console.log("授权结果",res.data);
              if (res.data.respCode == '0') {
                getPicList(that);

                that.setData({
                  itemClick: false,
                })
                scaleButton(that, 0, 0);
                wx.showToast({
                  title: '授权成功',
                  icon: 'none'
                })

                //授权成功后发送模板消息
              } else {
                wx.showToast({
                  title: '授权失败',
                  icon: 'none'
                })
              }
            },
            complete: function () {
              wx.hideLoading();
            }
          });
        } else {
          console.log("制止了改变")
        }
      }
    });
  },

  
  onImageClick: function(e){
    var that = this;
    var index = e.currentTarget.dataset.id;  //获取自定义的id 
    //console.log(this.data.imageinfo[index].id)
    var pictureId = this.data.imageinfo[index].id;
    var pictureUrl = this.data.imageinfo[index].personphoto;
    let pages = getCurrentPages();
    let prePage = pages[pages.length - 2];
    let show_button = false;
    //console.log(images[index].personphoto)
    that.data.personcheck = true; //审核通过的
    if (this.data.isRegister){
      //设置图片路径会报错
      prePage.setData({
        photoPath: images[index].personphoto,
        imageSelect: true,
        picId: pictureId,
      });
      wx.navigateBack({
        delta: 1,
      })
    }else{
      //从查看记录过来的
      var select = !this.data.imageinfo[index].select;
      var update = 'imageinfo[' + index + '].select';
      
      deleteIdList = [];
      // passExamineList = [];
      
     
      // console.log("pass2", passExamineList)

      that.setData({
        [update]: select,
      })
      for (var i = 0; i < that.data.imageinfo.length; i++) {
        // console.log("pass2", that.data.imageinfo)
        if (that.data.imageinfo[i].select) {
          deleteIdList.push(that.data.imageinfo[i].id)
          show_button = true;
          if (that.data.imageinfo[i].personcheck != 'Y') {
            that.data.personcheck = false; //需要点击审核
          }
        }
        
      }
      that.setData({
        itemClick: show_button,
        personcheck:that.data.personcheck
      })

      var x = 0;
      var y = 0;
      if (show_button) {
        x = 1;
        y = 1;
      } else {
        x = 0;
        y = 0;
      }
      scaleButton(this, x, y);

    }
    
  }
})

// var passExamineList = [];
var deleteIdList = [];
var images = [];
function getPicList(that){
  var imageList = [];
  images = [];
  wx.showLoading({
    title: '加载中',
  })
  wx.request({
    url: Constant.BASEURL + Constant.VISITOR_PICTURE_URL + "&openid=" + app.globalData.openid,
    method: 'GET',
    success: function (res) {
      console.log("bbbb",res.data)
      if (Array.isArray(res.data.data)){
        for (var i = 0; i < res.data.data.length; i++) {
          var id = res.data.data[i].id;
          var url = Constant.BASEURL + "/" + res.data.data[i].personphoto;
          var select = false;

          console.log("开始时间：", res.data.data[i])
          var personstarttime = res.data.data[i].starttime;
          var personendtime = res.data.data[i].endtime;
          imageList.push({ 'id': id, 'personphoto': url, "select": select, 'starttime': personstarttime, 'endtime': personendtime, "personcheck": res.data.data[i].personcheck});
          images.push({ 'personphoto': res.data.data[i].personphoto });
        }
        that.setData({
          imageinfo: imageList,
        })
        wx.hideLoading();
        wx.stopPullDownRefresh();
        if (res.data.data.length < 1) {
          wx.showToast({
            title: '没有查询到访客申请记录',
            icon: 'none'
          })
        }
      }else{
        wx.hideLoading();
        wx.stopPullDownRefresh();
        wx.showToast({
          title: '没有查询到访客申请记录',
          icon: 'none'
        })
      }
      
    },
    fail: function (res) {
      console.log(res.errMsg)
      wx.hideLoading();
      wx.stopPullDownRefresh();
    },
    
  })
}

function getLocalTime(nS) {
  var mDate = new Date(nS);
  
  // mDate.getMonth();
  // mDate.getDay();
  // mDate.getHours();
  // mDate.getMinutes();
  // var time = mDate.getYear() + "/" + mDate.getDay() + "/" + mDate.getHours() + "/" + 
  return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
}

function scaleButton(that, x, y) {
  //创建动画
  var animation = wx.createAnimation({
    duration: 500,
    timingFunction: "ease",
    delay: 0,
    transformOrigin: "50% 50%",
  })
  animation.scale(x, y).step();     //边旋转边放大
  that.setData({
    animationData: animation.export(),
  })
}

function sendPassMsg() {
  wx.request({
    url: Constant.SEND_MODEL_MSG,
    method: 'POST',
    data:{
      "touser": app.globalData.openid, //接受的openid
      "template_id": 'WOKthI4kzJpx3v-dLxV-mj4pyJLLrUg393z3PIPvAwM-9I3X4JUWudEfc', // 所需下发的模板消息的id
      "data": {
        "keyword1": {
          "value": "大帅哥",
          "color": "#173177"
        },
        "keyword2": {
          "value": "微信小程序分享",
          "color": "#173177"
        },
        "keyword3": {
          "value": "无",
          "color": "#173177"
        },
        "keyword4": {
          "value": "审核通过",
          "color": "#173177"
        },
        "keyword5": {
          "value": "20180101",
          "color": "#173177"
        },
         "keyword6": {
           "value": "20180102",
          "color": "#173177"
        }
      }
    }
  })
}